package com.dinero.pagecontents.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.ContactsContract
import android.util.Log
import android.view.KeyEvent
import android.view.View
import com.android.basekt.base.BaseDataBindingConfig
import com.dinero.pagecontents.R
import com.dinero.pagecontents.base.BaseActivity
import com.dinero.pagecontents.view.TipsDialog
import com.dinero.pagecontents.databinding.ActivityCertifyContactInformationBinding
import com.dinero.pagecontents.viewmodel.CertifyPersonInformationViewModel
import com.permissionx.guolindev.PermissionX
import java.util.*

/**
 * @Created on 2021/12/27 10:55
 * @Author
 * @Describe
 */
class CertifyContactInformationActivity :
    BaseActivity<ActivityCertifyContactInformationBinding, CertifyPersonInformationViewModel>(),
    View.OnClickListener {
    override fun initView() {
        mComplete = intent.getStringExtra("complete").toString()
        var proId = intent.getStringExtra("proId").toString()
        mViewModel.mProId.value = proId
        mViewModel.mContext = this
        mViewModel.mSelectContent.observe(this) {
            if (isFristContact) {
                mViewModel.mFristContact.value = it
            } else {
                mViewModel.mTwoContact.value = it
            }
        }
        mViewModel.mFinishFilter.observe(this) {
            if (it == true) {
                finishFilter()
            }
        }

        mBinding.viewModel = mViewModel

        mBinding.listener = this

        mBinding.apply {
            viewModel = mViewModel
        }

    }

    val tipsDialog by lazy {
        TipsDialog(
            title = "Nota",
            tips = "¿Está seguro/a de que desea salir del certificado? Completar los datos de autorización aumentará la posibilidad de conseguir el préstamo.",
            left = "Confirmar",
            right = "Cancelar"
        ).apply {
            setLeftListener {
                finishView()
            }
        }
    }
    var mComplete: String = ""
    fun finishFilter() {
        if(mComplete=="1"){
            finishView()
        }else{
            tipsDialog.show(supportFragmentManager, "")
        }
    }
    override fun initData() {

        var title = intent.getStringExtra("title")
        Log.i("title", "initData: title====>${title}")
        title?.let {
            mViewModel.mTitleContent.value = it
        }

        mViewModel.getContactDatas()

//        val reqPermissions: MutableList<String> = ArrayList()
//        if (!PermissionX.isGranted(this, Manifest.permission.READ_CONTACTS)) {
//            reqPermissions.add(Manifest.permission.READ_CONTACTS)
//        }
//        PermissionX.init(this)
//            .permissions(reqPermissions)
//            .request { allGranted, grantedList, deniedList ->
//                if (allGranted) {
//                }
//            }
    }


    var TAG = "checkPermission"
    fun checkPermission() {
        val reqPermissions: MutableList<String> = ArrayList()
        if (!PermissionX.isGranted(this, Manifest.permission.READ_CONTACTS)) {
            reqPermissions.add(Manifest.permission.READ_CONTACTS)
        }

        Log.i(TAG, "checkPermission: " + reqPermissions.size)

        PermissionX.init(this)
            .permissions(reqPermissions)
            .request { allGranted, grantedList, deniedList ->
                Log.i(TAG, "checkPermission:${allGranted} ")
                if (allGranted) {
                    goToContact()
                }
            }
    }


    fun goToContact() {
        val intent = Intent()
        val uri = Uri.parse("content://contacts")
        intent.action = Intent.ACTION_PICK
        intent.data = uri
        intent.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
        startActivityForResult(intent, 1111)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1111) {
            if (data != null) {
                val uri = data.data
                val result = getPhoneContacts(this, uri)
                result?.let {
                    Log.i(TAG, "onActivityResult: ${result[0]}, ${result[1]}")
                    if (isFristContact) {
                        mViewModel.mFristContactName.value = result[0]
                        mViewModel.mFristContactPhone.value = result[1]
                    } else {
                        mViewModel.mTwoContactName.value = result[0]
                        mViewModel.mTwoContactPhone.value = result[1]
                    }
                }

            }
        }
    }

    fun getPhoneContacts(context: Context, uri: Uri?): Array<String?>? {
        val contact = arrayOfNulls<String>(2)
        val cr = context.contentResolver
        val cursor = cr.query(
            uri!!, arrayOf(
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
            ), null, null, null
        )
        if (cursor != null) {
            cursor.moveToFirst()
            if (cursor.count > 0) {
                do {
                    contact[0] = cursor.getString(0)
                    contact[1] = cursor.getString(1)
                } while (cursor.moveToNext())
            }
            cursor.close()
        } else {
            return null
        }
        return contact
    }

    /**
     * 获取binding相关配置
     *
     * @return
     */
    override fun getDataBindingConfig(): BaseDataBindingConfig {
        return BaseDataBindingConfig(R.layout.activity_certify_contact_information)
    }

    /**
     * 获取viewmodel Clazz
     *
     * @return
     */
    override fun initViewModelClazz(): Class<CertifyPersonInformationViewModel> {
        return CertifyPersonInformationViewModel::class.java
    }

    var isFristContact = true
    override fun onClick(v: View?) {

        when (v?.id) {
            R.id.ll_contanct_num_1 -> {
                isFristContact = true
                checkPermission()
            }
            R.id.ll_contanct_num_1_1 -> {
                isFristContact = true
                checkPermission()
            }

            R.id.ll_contanct_num_1_2 -> {
                isFristContact = true
                mViewModel.showEnumView(mViewModel.mFristContactDatas)
            }

            R.id.ll_contanct_num_2, R.id.ll_contanct_num_2_1 -> {
                isFristContact = false
                checkPermission()
            }
            R.id.ll_contanct_num_2_2 -> {
                isFristContact = false
                mViewModel.showEnumView(mViewModel.mTwoContactDatas)
            }
        }
    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(mComplete!="1"){
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                tipsDialog.show(supportFragmentManager, "")
                return false
            }
        }
        return super.onKeyDown(keyCode, event)
    }

}